package com.misty.reflect;

import org.junit.Test;

import java.lang.reflect.Field;

public class FieldTest {
    /**
     * 测试公有属性
     */
    @Test
    public void demo(){
        try {
            //获得Class
            Class class1 = Class.forName("com.imist.Man");
            //这里获取的是公有属性
            Field nameField = class1.getField("name");
            //操作属性 man.name = " ";
            Man man1 = (Man) class1.newInstance();
            //给一个实例的指定属性赋值
            nameField.set(man1,"iMist");//man1.name = "iMist";
            //得到并打印实例的属性
            System.out.println(nameField.get(man1));

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试私有的属性
     */
    @Test
    public void demo2(){
        try {
            Class class1 = Class.forName("com.imist.Man");
            Field sexField = class1.getDeclaredField("sex");
            Man man = (Man) class1.newInstance();
            sexField.setAccessible(true);
            sexField.set(man,23);

            System.out.println(sexField.get(man));
            System.out.println(man);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
}
